﻿using System;
using System.Linq;
using System.Web.Mvc;
using System.Web;
using Developer.Entity;
using Developer.Service;
using Super.Framework.Common.Secure;
using Super.Framework.Common.Web;

namespace Developer.Web.Areas.Admin.Controllers
{
    public class HomeController : BaseController
    {
        // GET: Admin/Home
        public ActionResult Index()
        {
            var loginUser = SysInfo.LoginUser;
            ViewBag.Account = loginUser.Account;
            return View();
        }

        public ActionResult Login()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Login(int? z)
        {
            var account = Query.Value("account");
            var password = Query.Value("password");

            var pwd = password.Md5String();

            var user = SysInfo.DB.Adminers.FirstOrDefault(a => a.Account == account && a.Password == pwd);
            if (user == null)
            {
                ShowMsg("账号密码错误", MessageItemType.Error);
                return View();
            }
            var ip = Query.IP;
            var agent = Query.ClientInfos.Agent;
            var token = SecurityService.GenerateToken(account, pwd, ip, agent, DateTime.Now.AddDays(7).Ticks);
            //用UserIdentity代表管理员身份，仅限管理员
            SysInfo.LoginUser = new LoginUser { Id = user.Id, Account = account, Token = token, Entity = user};

            return Redirect("/admin/home/index");

        }

        public ActionResult LogOut()
        {
            var logout = SysInfo.Logout;
            return Redirect("/admin/home/login");
        }

        public ActionResult InitAccount()
        {
            var user = new Adminers();
            user.Account = "admin";
            user.Password = "000000".Md5String();
            user.CreateTime = DateTime.Now;
            SysInfo.DB.Adminers.Add(user);
            SysInfo.DB.SaveChanges();
            return Content("/admin/home/login");
        }

        public ActionResult PersonalInfo()
        {
            var account = Query.Value("account");
            var user = AdminerService.GetAll().FirstOrDefault(a => a.Account == account);
            if (user != null)
            {
                return View(user);
            }
            ShowMsg("该账户不存在,请重新登陆！", MessageItemType.Error);
            return Redirect("/admin/home/login");
        }
        [HttpPost]
        public ActionResult InfoEdit(FormCollection fc)
        {
            var password = Query.Value("password");
            return View();
        }
    }
}